<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
    public function index(){
        indexRvent();//测算首页执行事件
        //$this->deleteSessions();//缓存清理
        indexRequest($_REQUEST);//测算首页接收数据处理

        $csNumberArr=array(
            'bzjpcs','bzcycs','bzhhcs','bzsycs','hyzscs','lnyccs','xmcscs','zwdscs','lathcs','xzcscs','bbqmcs','pfccs','szjxcs','mrbzcs','lnyc2020cs','bzhycs','sndycs','sssdcs',
        );
        foreach($csNumberArr as $key=>$value){
            csRandNum($value); //随机数
        }

        $channel=cookie('channel');

        //渠道获取ID
        $channelID=obtain_channelID('Index');
        $this->assign('channelID',$channelID);

        if($_REQUEST['type']){
            cookie('indexType',$_REQUEST['type']);
        }
        $type=cookie('indexType');

        //渠道换版本颜色
        if($channel=='qudao305'){$type=2;}

        cookie('qudaoJgTypeNum',1);//结果页标识修改  1为首页

        if(cookie('jploginHC')==''){
            cnzz_pvuv('Index');//执行统计
            cookie('loginIndex',1,30);
        }
        $this->assign('channel',$channel);

        if($type==2){
            $this->display("Index/ZM_mingli_shouye2");
        }else if($type==3){
            $this->display("Index/ZM_mingli_shouye3");
        }else{
            $this->display("Index/ZM_mingli_shouye1");
        }
    }
    public function mycesuan1(){//链接被封 中转
        $this->mycesuan();
    }
    public function mycesuan(){//我的测算
        $this->assign('titleName',titleName('wdcs',4));//标题名称
        indexRequest($_REQUEST);//测算首页接收数据处理
        $channel=cookie('channel');

        if(cookie('jploginHC')==''){
            cnzz_pvuv('mycesuan');//执行统计
            cookie('jploginHC',1,5);
        }

        if($_REQUEST['orderid']){
            $orderid=$_REQUEST['orderid'];
            $csName=$_REQUEST['csName'];
            $csUrl=U($csName.'/jieguoye','',false).'?ordernum='.$orderid;

            $this->assign('orderid',$orderid);
            $this->assign('csName',$csName);
            $this->assign('csUrl',$csUrl);
        }

        $user_agent = $_SERVER['HTTP_USER_AGENT'];//用户使用的浏览器，操作系统等信息。
        if (strpos($user_agent, 'MicroMessenger') == false) {
            //非微信浏览器访问
            cookie('wxlogin',0);
        }else{
            cookie('wxlogin',1);
            getToken();
            getTicket();
            $wzurl=wxJsdkData();
            if(!empty($_REQUEST['code'])){
                cookie('code',$_REQUEST['code'],7100);
            }
            getCode($wzurl);
            getOopenid();
            cookie('uid',cookie('openid'));

            //本页面隐藏热门推荐
            cookie('hideAllHotNum',1,5);
        }

        $uid=cookie('uid');
        $uidArr=S('sm_h5test|'.$uid);

        krsort($uidArr);
        if($uid!=''){
            $i=0;
            $arr=array();
            foreach($uidArr as $key=>$value){
                $orderArr=S($value);
                if($i>=10){break;}
                if($orderArr['status']==1&&$orderArr['price']>0){$i++;
                    $arr[$key]=$orderArr;
                }
            }

            //运势运程订单
            $url="http://wx1.bazijingpi.top/ysyc/index.php/index/Jiekou/myOrder?uid={$uid}";
            $ch = curl_init();
            curl_setopt($ch,CURLOPT_URL,$url); //设置请求地址
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//不需要证书验证
            curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//不直接输出到页面
            $json = curl_exec($ch);
            $jsonArr=json_decode($json,true);
            $arr=array_merge($arr,$jsonArr);

            $arr=array_values($arr);
            $arrCount=count($arr);

            //dump($arr);exit;

            $i=0;
            foreach($uidArr as $key=>$value){
                $orderArr=S($value);
                if($i>=10){break;}
                if($orderArr['status']!=1&&$orderArr['price']>0){$i++;
                    $arr[$arrCount+$i]=$orderArr;
                }
            }
        }

        $arr=array_filter($arr);

        $freeUrlArr=array(
            0=>array('name'=>'八字精批', 'url'=>U("Bzjp/jieguoye",'',false),),
            1=>array('name'=>'八字合婚', 'url'=>U("Bzhh/jieguoye",'',false),),
            18=>array('name'=>'八字财运', 'url'=>U("Bzcy/jieguoye",'',false),),
            38=>array('name'=>'每月运势', 'url'=>U("Myys/jieguoye",'',false),),
        );
        foreach($arr as $key=>$value){
            if($value['status']==2){
                $arr[$key]['name']=$freeUrlArr[$value['typeid']]['name'];
                $arr[$key]['url']=$freeUrlArr[$value['typeid']]['url']."?ordernum={$value['ordernum']}";
            }
        }

        $this->assign('arr',$arr);
        if($channel=='vivo'){
            $this->display("Index/ZM_mycesuan_vivo");
        }else{
            $this->display("Index/ZM_mycesuan");
        }
    }
    public function select(){//查询操作
        $orderid=I('request.keyword');

        $arr[0]=jieguoyeArrData($orderid);

        if(empty($arr[0]['ordernum'])){
            $arr=M()->query("select ordernum,username,typeid,status from sm_h5test where  ordernum='{$orderid}' order by id desc limit 1");
        }

        if(empty($arr)){
            $str2=mb_substr($orderid,0,2);
            $str4=mb_substr($orderid,0,4);
            $str5=mb_substr($orderid,0,5);
            $str6=mb_substr($orderid,0,6);
            if($str6=='BZJPPT'){//二次支付
                $arr=M()->query("select ordernum,status,kind from sm_h5test_jp_config where payordernum='{$orderid}'");
                $arrKind=array(
                    1=>'2020运势', 2=>'每月运势', 3=>'紫微运势',
                );
                if($arr[0]['status']==1){
                    $arr[0]['name']='八字精批—'.$arrKind[$arr[0]['kind']];
                    $arr[0]['typeid']=100;
                    $arr[0]['orderid']=$arr[0]['ordernum'];
                    $arr[0]['url']="http://wx1.bazijingpi.top/zhiming/index.php/home-bzjp-jieguoye?ordernum={$arr[0]['ordernum']}";
                }
            }elseif($str5=='LQAPP'){//灵旗APP
                $arr=M()->query("select ordernum,status,type,username from data_app_tool_order where ordernum='{$orderid}'");
                if($arr[0]['status']==1){
                    $type=$arr[0]['type'];
                    $typeJgUrl=array(
                        1=>'http://wx1.bazijingpi.top/webH5/lingqiyixue/#/pages/zwds/index',
                        2=>'http://wx1.bazijingpi.top/webH5/lingqiyixue/#/pages/bzfx/fenxi',
                        4=>'http://wx1.bazijingpi.top/webH5/lingqiyixue/#/pages/qzsy/index',
                        5=>'http://wx1.bazijingpi.top/webH5/lingqiyixue/#/pages/qmdj/index',
                    );
                    $arr[0]['name']='灵旗排盘';
                    $arr[0]['typeid']=100;
                    $arr[0]['orderid']=$orderid;
                    $arr[0]['url']=$typeJgUrl[$type]."?orderid={$orderid}";
                }
            }elseif($str2=='LQ'){
                $arr=M()->query("select orderid,status from lq_h5text where orderid='{$orderid}'");
                if($arr){
                    $arr[0]['name']='灵签';
                    $arr[0]['typeid']=100;
                    $arr[0]['url']="http://wx1.bazijingpi.top/webH5/Lingqian/#/lot-detail?orderid={$orderid}";
                }
            }elseif($str2=='KY'){
                $arr=M()->query("select orderid,status,uid from shop_h5test where orderid='{$orderid}'");
                if($arr){
                    $arr[0]['name']='开运香';
                    $arr[0]['typeid']=100;
                    $arr[0]['url']="http://wx1.bazijingpi.top/interface/index.php/Home/Kaiyun/index?uid={$arr[0]['uid']}";
                }
            }elseif($str2=='JC'){
                $arr=M()->query("select orderid,status from jc_h5test where orderid='{$orderid}'");
                if($arr){
                    $arr[0]['name']='趣味测';
                    $arr[0]['typeid']=100;
                    if($arr[0]['status']==1){
                        if(substr($orderid,2,2)>=11){
                            $arr[0]['url']="http://wx1.bazijingpi.top/jianceH5/testResult.html?orderid={$orderid}";
                        }else{
                            $arr[0]['url']="http://wx1.bazijingpi.top/jianceH5/testResultQWC.html?orderid={$orderid}";
                        }
                    }else{
                        //$arr[0]['url']="";
                    }
                }
            }elseif($str2=='QW'){
                $arr=M()->query("select ordernum,status,subject from qc_pay_order where ordernum='{$orderid}'");
                $subject=$arr[0]['subject'];
                $nameArr=array('QWCS22F'=>'疾病预测',);
                $urlArr=array('QWCS22F'=>"http://wx1.bazijingpi.top/quce/index.php/home-paycs-jieguoye?orderid={$orderid}",);
                if($arr){
                    if($nameArr[$subject]){
                        $arr[0]['name']=$nameArr[$subject];
                        $arr[0]['typeid']=100;
                        $arr[0]['orderid']=$orderid;
                        $arr[0]['url']=$urlArr[$subject];
                    }else{
                        $arr[0]['name']='综合趣测';
                        $arr[0]['typeid']=100;
                        $arr[0]['url']="http://wx1.bazijingpi.top/quce/index.php/Home-Index-mytest?orderid={$orderid}";
                    }
                }
            }elseif(is_numeric($str2)){//是数字订单  AI面相/手相
                $url="http://face.yixueqm.com/app/index.php?i=1&c=entry&do=cs&m=hc_face&cType=interfaceSelectOrderZm&orderid={$orderid}";
                $data=curlGet($url);
                $data=json_decode($data,true);
                if($data['code']==1){
                    $arr[0]['name']='AI面相/手相';
                    $arr[0]['typeid']=100;
                    $arr[0]['url']=$data['url'];
                    $arr[0]['status']=1;
                    $arr[0]['orderid']=$orderid;
                }
            }else{

            }
        }
        if($_REQUEST['number']==1){//ajax回调
            if(empty($arr[0])){
                echo '1';
            }else{echo '2';}
            exit;
        }

        $this->assign('arr',$arr);
        $this->display("Index/ZM_mycesuan");
    }

    public function selectLoop(){//循环查询是否支付
          $orderid=$_REQUEST['orderid'];
        if(mb_substr($orderid,0,4)=='YSYC'){//运势运程订单
            $url="http://wx1.bazijingpi.top/ysyc/index.php/index/Index/selectLoop?orderid={$orderid}";
            $ch = curl_init();
            curl_setopt($ch,CURLOPT_URL,$url); //设置请求地址
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//不需要证书验证
            curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//不直接输出到页面
            $json = curl_exec($ch);
            echo $json;
        }else{
            $arrdata=S('sm_h5test|'.$orderid);
            if(S($orderid)){
                echo 1;
                if(S('orderReeor')==$orderid){//容错 支付成功后没有订单
                    orderError($orderid);
                }
                S($orderid,null);
            }elseif($arrdata['status']==1){
                echo 1;
            }else{
                echo 0;
            }
        }
    }

    public function select_pay(){//微信支付json返回
        $arr=M()->query("select status from sm_h5test where ordernum='".$_REQUEST['orderid']."' limit 1");
        $data=$arr[0]['status'];
        if($data!=1){
            $data=2;
        }
        echo $data;
    }
//    public function addphoneoremail(){//订单绑定手机或者邮箱
//        M()->query("insert into tb_phone_or_email values(null,'{$_REQUEST['orderid']}','{$_REQUEST['value']}')");
//        echo '1';
//    }
//    public function user_evaluate(){//用户评价
//        $content=I('request.content');
//        M()->query("insert into tb_user_evaluate (orderid,evaluate,fraction)values('{$_REQUEST['orderid']}','{$content}',{$_REQUEST['raty']})");
//        echo '1';
//    }
//    public function shouhoufuwu(){
//        $username=I('request.username');
//        $content=I('request.content');
//        $contact_wx=I('request.contact_wx');
//        $contact_email=I('request.contact_email');
//        $contact_phone=I('request.contact_phone');
//        M()->query("insert into tb_shouhoufuwu values(null,'{$username}','{$_REQUEST['payment_time']}',{$_REQUEST['typeid']},'{$content}',{$_REQUEST['contact_type']},'{$contact_wx}','{$contact_email}','{$contact_phone}',now())");
//        $this->display("Index/ZM_shouhoufuwu");
//    }


    public function return_urlwx(){//同步回调
        if($_REQUEST['out_trade_no']){
            $orderid=$_REQUEST['out_trade_no'];
        }else{
            $orderid=$_REQUEST['orderid'];
            $csName=$_REQUEST['csName'];
        }

        $data=mb_substr($orderid,0,2,'utf-8');
        $dataThree=mb_substr($orderid,0,3,'utf-8');
        $dataFour=mb_substr($orderid,0,4,'utf-8');
        $data5=mb_substr($orderid,0,5,'utf-8');
        $dataSix=mb_substr($orderid,0,6,'utf-8');

        if($dataFour=='QMHZ'){//百度合作
            redirect(U('Bbqm/bdIndex','',false)."?orderid={$orderid}");
        }elseif($dataSix=='BZJPPT'){//结果二次支付
            $Zorderid=S($orderid.'Zorderid');
            redirect(U('Bzjp/jieguoye','',false)."?ordernum={$Zorderid}&typeName=BZJPPT");
        }

        if(S('sm_h5test_type'.$dataFour)){
            $typeArr=S('sm_h5test_type'.$dataFour);
        }else{
            $typeArr=M()->query("select csName from sm_h5test_type where shortname='{$dataFour}'");
            if(empty($typeArr)){$typeArr=M()->query("select csName from sm_h5test_type where shortname='{$dataThree}'");}
            if(empty($typeArr)){$typeArr=M()->query("select csName from sm_h5test_type where shortname='{$data}'");}
            if(empty($typeArr)){$typeArr=M()->query("select csName from sm_h5test_type where shortname='{$data5}'");}
            if($typeArr){
                S('sm_h5test_type'.$dataFour,$typeArr,86400);
            }
        }

        if($typeArr&&!$csName){$csName=$typeArr[0]['csName'];}
        if($csName){
            $jumpUrl=U("{$csName}/jieguoye",'',false)."?ordernum={$orderid}";
        }else{
            $jumpUrl=0;
        }

        //$arr=M()->query("select id,typeid from sm_h5test where ordernum='{$orderid}' and status=1");
        $arr=S('sm_h5test|'.$orderid);

        if($dataFour=='MR37'){//名人同命
            if(empty($arr)){header("location:https://{$_SERVER['HTTP_HOST']}/webH5/Mrtm/#/mrDatum");
            }else{header("location:https://{$_SERVER['HTTP_HOST']}/webH5/Mrtm/#/mrResultEnd?orderid={$orderid}");}
        }


        if($arr['status']!=1){
            header('location:'.U('Index/mycesuan','',false)."?orderid={$orderid}&csName={$csName}");exit;
        }


        if($data=='QS'&&$arr[0]['typeid']==26){
            header('location:'.U('Bzjp/payzfEnd','',false));
        }else if($csName){
            header('location:'.$jumpUrl);
        }else{
            header('location:'.U('Index/mycesuan','',false));
        }
    }
    public function notify_urlwx(){//异步回调
        $xmldata=file_get_contents("php://input");
        $trade_no=$_REQUEST['trade_no'];

        if($_REQUEST['orderid']&&empty($_REQUEST['billno'])){//第三方订单
            $ordernum=$_REQUEST['orderid'];
            if($_REQUEST['billno']){
                $ordernum=$_REQUEST['billno'];
                $transactionId=$_REQUEST['orderid'];
                file_put_contents("./Upload/notify_url{$ordernum}.txt",json_encode($_REQUEST));
            }
            $paykind=3;//第三方
        }else if($_REQUEST['out_trade_no']){//支付宝订单
            $ordernum=$_REQUEST['out_trade_no'];
            $transactionId=$_REQUEST['trade_no'];
            //file_put_contents("./Upload/notify_urlZFB.txt",json_encode($_REQUEST));
            if($_REQUEST['app_id']=='2016101302144443'&&$_REQUEST['trade_status']=='TRADE_SUCCESS'){//过虑
            }else{
                echo 'false';exit;
            }
            //file_put_contents("./Upload/notify_urlAppid.txt",$_REQUEST['app_id']);
            $paykind=1;

        }else if($xmldata){//微信订单
            $paykind=0;
            //$strData = $GLOBALS["HTTP_RAW_POST_DATA"];//接收到xml数据
            $strData =$xmldata;//接收到xml数据
            //万娱合作
            $arrWY=explode('&',$strData);
            if($arrWY[0]){
                foreach($arrWY as $key=>$value){
                    $wyData=explode('=',$value);
                    $arrWYData[$wyData[0]]=$wyData[1];
                }
                $billno=$arrWYData['billno'];
                $ordernum=$billno;
                $transactionId=$arrWYData['orderid'];
                if($transactionId){
                    $paykind=3;//第三方
                }
            }

//            $time=time();
//            file_put_contents("./Upload/notify_urlwxData{$time}.txt",$strData);

            $obj = simplexml_load_string($strData);//把xml字符串解析成对象
            $valuesArr = json_decode(json_encode(simplexml_load_string($xmldata, 'SimpleXMLElement', LIBXML_NOCDATA)), true);//把xml字符串解析成数组

            //$ordernum=$obj->out_trade_no;
            //file_put_contents("./Upload/notify_urlwxOgjwxArr.txt",json_encode($valuesArr));
            if($valuesArr['out_trade_no']){
                $ordernum=$valuesArr['out_trade_no'];
                $transactionId=$valuesArr['transaction_id'];
                $trade_type=$valuesArr['trade_type'];
                if($valuesArr['result_code']!='SUCCESS'){echo 0;exit;}
            }

            if($obj->trade_type=='MWEB'||$obj->trade_type=='NATIVE'){//H5支付模式 扫码
                S($ordernum,'1',300);//是否支付判断缓存
            }

            //if(empty($ordernum)){//qudao135返回json数据   第三方支付回调

                $obj=json_decode($strData);
                if($obj->extContent){
                    file_put_contents('./Upload/zhiming_notify135.txt',$strData);
                    if($obj->orderStatus==1){
                        $ordernum=$obj->extContent;
                        $transactionId=$obj->orderNum;
                        $str135=mb_substr($ordernum,0,2);
                        if($str135=='JC'){
                            $updateTime=date("Y-m-d H:i:s");
                            M()->query("update jc_h5test set status=1,paykind='{$paykind}',updatetime='{$updateTime}' where orderid='{$ordernum}'");
                            echo 'success';
                            exit;
                        }
                    }
                }
            //}
        }

        if(empty($ordernum)){//为空
            echo 'error:订单号为空';exit;
        }

        $dataFour=mb_substr($ordernum,0,4,'utf-8');
        $dataSix=mb_substr($ordernum,0,6,'utf-8');
        //百度合作
        if($dataFour=='QMHZ'){
            S($ordernum.'status',1,120);
            M()->query("update sm_h5test_baidu set status=1,transaction_id='{$transactionId}',updatetime=now() where orderid='{$ordernum}'");
            exit;
        }
        //结果二次支付
        if($dataSix=='BZJPPT'){
            $Zorderid=S($ordernum.'Zorderid');
            S($ordernum.'status',1,120);
            M()->query("update sm_h5test_jp_config set status=1,transaction_id='{$transactionId}',updatetime=now(),paykind='{$paykind}' where payordernum='{$ordernum}'");
            $orderJpConfigArr=M()->query("select kind from sm_h5test_jp_config where payordernum='{$ordernum}'");
            $kind=$orderJpConfigArr[0]['kind'];
            $selectArr[0]=jieguoyeArrData($Zorderid);
            $selectArr[0]["kind{$kind}"]=1;
            $saveTime=C('saveTime');//保存时间
            S('sm_h5test|'.$Zorderid,$selectArr[0],$saveTime);

            echo 'BZJPPT';
            exit;
        }

        $selectArr[0]=S('sm_h5test|'.$ordernum);
        $channel=$selectArr[0]['channel'];
        $uid=$selectArr[0]['appuserid'];
        $price=$selectArr[0]['price'];
        $createtime=$selectArr[0]['createtime'];

        S($ordernum,'1',300);//是否支付判断缓存
        if(empty($createtime)&&empty($price)){
            S('orderReeor',$ordernum,600);//容错 支付成功后没有订单
            //dump($selectArr);
            $selectArr[0]['paykind']=$paykind;
            file_put_contents("./Upload/zhiming_notifyNo{$ordernum}.txt",json_encode($selectArr,JSON_UNESCAPED_UNICODE));
            echo 'error:没有订单';exit;
        }

        if($channel=='qudao245'){
            echo '{"message":"ok"}';
        }elseif($billno){
            echo json_encode(array("status"=>"success","msg"=>''));
        }else{
            echo 'success';
        }

        if($selectArr[0]['date_remark']=='discountQczh'){//趣测优惠券订单
            S($uid.'discountQczh',1,2592000);
        }

        if($selectArr[0]['areaes']){//是不是优惠券
            $code=$selectArr[0]['areaes'];
            M()->query("update tb_coupon set toUse=1 where code='{$code}'");
        }

        //是不是分享赚
        $zhuanArr=S('tb_zhuan_share_user'.$selectArr[0]['appuserid']);
        if($zhuanArr){
            $typeid=$selectArr[0]['typeid'];
            $price=$selectArr[0]['price'];
            $uid=$selectArr[0]['appuserid'];
            $shareUid=$selectArr[0]['date_remark'];
            $shareCstypeArr=array(
                0=>'bzjp',34=>'lnyc2019',
            );
            $shareUserArr=S('tb_zhuan_share_user'.$uid);
            $paidCs=$shareUserArr[0]['paidCs'];
            if(stristr($paidCs,$shareCstypeArr[$typeid])){
            }else{
                M()->query("update tb_zhuan_share_user set paidCs='{$paidCs}|{$shareCstypeArr[$typeid]}' where uid='{$uid}'");
            }

           // M()->query("update tb_zhuan_share_user set {$shareCstypeArr[$typeid]}=0 where uid='{$uid}'");

            if(mb_substr($shareUid,0,5)=='Share'){
                $ShareController=A('Share');
                $ShareController->adddivideinto($shareUid,$ordernum,$price);
            }
        }

        $csTypeid=$selectArr[0]['typeid'];

        //已支付结束执行
        if($selectArr[0]['status']==1){exit;}

        //测算类型获取
        $typeArr[0]['shortname']=S('sm_h5test_type'.$csTypeid);
        if(empty($typeArr[0]['shortname'])){
            $typeArr=M()->query("select * from sm_h5test_type where id='{$selectArr[0]['typeid']}'");
            $csName=$typeArr[0]['shortname'];
            S('sm_h5test_type'.$csTypeid,$typeArr[0]['shortname'],86400);
        }
        if(empty($csName)){$csName=$typeArr[0]['shortname'];}

        $strData=mb_substr($ordernum,0,2);
        if($strData=='JP'&&$selectArr[0]['price']>100){
            exit;
        }

        if(isset($trade_no)){//第三方订单记录
            //file_put_contents("./Upload/trade_no.txt",$trade_no.'-'.$ordernum);
            //$selectArr[0]['remark']=$trade_no;
            $transactionId=$trade_no;
        }

        //改订单支付状态
        $updateTime=date("Y-m-d H:i:s");
        $selectArr[0]['status']=1;
        $selectArr[0]['paykind']=$paykind;
        $selectArr[0]['updatetime']=$updateTime;
        $selectArr[0]['transaction_id']=$transactionId;
        $selectArr[0]['areaes']=$trade_type;

        //成功订单记录
        if($paykind<=2){
            $jsonText=json_encode($selectArr[0],JSON_UNESCAPED_UNICODE);
            M()->query("insert into sm_h5test_wx_orderid (orderid,text)values('{$ordernum}','{$jsonText}')");
            if($strData=='HH'||$strData=='HY'){//合婚或者婚缘执行
                $jsonText2=json_encode(S('sm_h5test|'.$ordernum.'_'),JSON_UNESCAPED_UNICODE);
                M()->query("insert into sm_h5test_wx_orderid (orderid,text)values('{$ordernum}_','{$jsonText2}')");
            }
        }

        if($channel=='qudao245'){//趣头条渠道改变
            if($paykind<3){
                $selectArr[0]['channel']=$channel.'_M';
            }
        }

        $saveTime=C('saveTime');//保存时间
        S('sm_h5test|'.$ordernum,$selectArr[0],$saveTime);

        if($strData=='HH'||$strData=='HY'){//合婚或者婚缘执行
            $FselectArr=S('sm_h5test|'.$ordernum.'_');
            $FselectArr['status']=1;
            S('sm_h5test|'.$ordernum.'_',$FselectArr,$saveTime);
        }
        //支付订单判断入库数组
        $insertTotalIndexArr=S('ZFinsertTotalIndexArr');
        if(empty($insertTotalIndexArr)){$insertTotalIndexArr=array();}
        array_push($insertTotalIndexArr,'sm_h5test|'.$ordernum);
        if($strData=='HH'||$strData=='HY'){//合婚或者婚缘执行
            array_push($insertTotalIndexArr,'sm_h5test|'.$ordernum.'_');
        }
        S('ZFinsertTotalIndexArr',$insertTotalIndexArr,$saveTime);

        ZFinsertTotalIndexArr($ordernum);//支付缓存订单入库

        fenxiaotonji($channel,$ordernum,$price,$createtime,$uid);//分销统计回调


        //扣量标识
        if(empty($csName)){$csName=mb_substr($ordernum,0,2);}
        if(S('tb_deduction_num'.$csName.$channel)){
            $deduArr=S('tb_deduction_num'.$csName.$channel);
        }else{
            $deduArr=M()->query("select * from tb_deduction_num where csName='{$csName}' and channel='{$channel}'");
            S('tb_deduction_num'.$csName.$channel,$deduArr,3600);
        }

        if($deduArr[0]['id']){
            $deduction=$deduArr[0]['clName'];
            if($deduction<1){
                $number=rand($deduArr[0]['num1'],$deduArr[0]['num2']);
                $deduArr[0]['clName']=$number;
                //M()->query("update tb_deduction_num set clName='{$number}' where id='{$deduArr[0]['id']}' ");
                $deduction=$number;
            }else{
                $deduction=$deduArr[0]['clName']-1;
                $deduArr[0]['clName']=$deduction;
                //M()->query("update tb_deduction_num set clName='{$deduction}' where id='{$deduArr[0]['id']}' ");
            }
            S('tb_deduction_num'.$csName.$channel,$deduArr,3600);
            if(S('tb_deduction_numNumber')==''){
                S('tb_deduction_numNumber',1,30);//更新时间
                M()->query("update tb_deduction_num set clName='{$deduction}' where id='{$deduArr[0]['id']}' ");
            }
            if($deduction==0){
                $selectArr[0]['place']=1;$selectArr[0]['minute']=$deduction;$selectArr[0]['channel']='androidcl';
                S('sm_h5test|'.$ordernum,$selectArr[0],2592000);
                //M()->query("update sm_h5test set status=1,place=1,minute='{$deduction}' where ordernum='{$ordernum}'");
                //扣量随机改渠道
                if($channel=='qudao275'){
                    M()->query("update sm_h5test set place=1 where ordernum='{$ordernum}'");
                }else{
                    M()->query("update sm_h5test set channel='androidcl{$channel}' where ordernum='{$ordernum}'");
                }
            }
        }


        //总价格统计入库
        $date=date('Ymd',strtotime($createtime));
        $yesterdayCX=date('Y-m-d 00:00:00',strtotime($createtime));
        $yesterdayCXlt=date('Y-m-d 23:59:59',strtotime($createtime));

        if(S('totalPriceNumber'.$csName.$channel)==''){
            S('totalPriceNumber'.$csName.$channel,1,600);

            $cnzzArr=M()->query("select id,totalPrice,transactionNum from tb_cnzz_pvuv where date='{$date}' and channel='{$channel}' and csName='{$csName}'");
            //$totalPrice=M()->query("select sum(price) price,count(id) id from sm_h5test where createtime >='{$yesterdayCX}' and createtime <='{$yesterdayCXlt}' and typeid='{$csTypeid}' and channel='{$channel}' and status=1 and (place is null or place='')");
            $totalPrice=M()->query("select sum(price) price,count(id) id from sm_h5test where createtime >='{$yesterdayCX}' and createtime <='{$yesterdayCXlt}' and typeid='{$csTypeid}' and channel='{$channel}' and status=1 and (place is null or place='')");
            if($totalPrice[0]['price']>0){
                M()->query("update tb_cnzz_pvuv set totalPrice='{$totalPrice[0]['price']}',transactionNum='{$totalPrice[0]['id']}' where id='{$cnzzArr[0]['id']}'");
            }
        }


//        if($selectArr[0]['remark']==2){//精批返回支付按钮统计
//            M()->query("update tb_cnzz_pvuv set bzjp_return_zhifu='{$cnzzArr[0]['bzjp_return_zhifu']}'+1 where id='{$cnzzArr[0]['id']}'");
//        }else if($selectArr[0]['remark']=='bzjp'){//精批跳姓名测试支付统计
//            M()->query("update tb_cnzz_pvuv set bzjp_xmcs_pay='{$cnzzArr[0]['bzjp_xmcs_pay']}'+1 where id='{$cnzzArr[0]['id']}'");
//        }
    }
    public function redisNotify(){//缓存订单状态修改
        //file_put_contents('./Upload/redisNotify.txt',json_encode($_REQUEST));
        if($_REQUEST['ordernum']||$_REQUEST['orderid']){
            if($_REQUEST['orderid']){
                $ordernum=$_REQUEST['orderid'];
            }else{
                $ordernum=$_REQUEST['ordernum'];
            }

            $selectArr[0]=S('sm_h5test|'.$ordernum);
            if(empty($selectArr[0])){
                echo 'error';
            }
            $username=$_REQUEST['username'];

            $encode = mb_detect_encoding($username, array("ASCII",'UTF-8','BIG5',"GBK",'BIG5','GB2312'));

            if($encode!='UTF-8'){
                $username=iconv('gb2312','utf-8//IGNORE',$username);
            }

            $updateData='';
            $year=$_REQUEST['year']?$_REQUEST['year']:$selectArr[0]['year'];
            if($year){$updateData.=",year='{$year}'"; $selectArr[0]['year']=$year;}
            $month=$_REQUEST['month']?$_REQUEST['month']:$selectArr[0]['month'];
            if($month){$updateData.=",month='{$month}'";$selectArr[0]['month']=$month;}
            $day=$_REQUEST['day']?$_REQUEST['day']:$selectArr[0]['day'];
            if($day){$updateData.=",day='{$day}'";$selectArr[0]['day']=$day;}

            $hour=$_REQUEST['hour'];

            if($hour||$hour==='0'){$updateData.=",hour='{$hour}'";$selectArr[0]['hour']=$hour;}
            if($_REQUEST['uid']){
                $uid=$_REQUEST['uid'];
                $updateData.=",appuserid='{$uid}'";$selectArr[0]['appuserid']=$uid;
            }
            $typeid=$_REQUEST['typeid'];
            if($typeid>0||$typeid===0){
                $selectArr[0]['typeid']=$typeid;
            }

            if($_REQUEST['kind']){
                $selectArr[0]['kind1']=1;
                $selectArr[0]['kind2']=1;
                $selectArr[0]['kind3']=1;
            }

            $status=$_REQUEST['status']?$_REQUEST['status']:$selectArr[0]['status'];
            if($_REQUEST['sex']===0||$_REQUEST['sex']==='0'||$_REQUEST['sex']){
                $sex=$_REQUEST['sex'];
            }else{
                $sex= $selectArr[0]['sex'];
            }
            if($sex){$updateData.=",sex='{$sex}'";}

            $strData=mb_substr($ordernum,0,2);

            //改订单支付状态
            $updateTime=date("Y-m-d H:i:s");
            if($strData=='XM'){//姓名测算
                if(empty($username)){
                    exit;
                }
                $username=mb_substr($username,0,1,'utf-8').'.'.mb_substr($username,1,2,'utf-8');
            }
            if($username){$updateData.=",username='{$username}'";  $selectArr[0]['username']=$username;}

            $selectArr[0]['sex']=$sex;
//            if($_REQUEST['status']){
//                $selectArr[0]['status']=$status;
//            }else{
//                $selectArr[0]['status']=1;
//                $status=1;
//            }
            $selectArr[0]['updatetime']=$updateTime;

            if($_REQUEST['status']==1){
                $paykind=2;
                $selectArr[0]['paykind']=$paykind;
                $selectArr[0]['status']=1;
                $updateData.=",status=1";
                $updateData.=",updatetime='{$updateTime}'";
                ZFinsertTotalIndexArr($ordernum);//支付缓存订单入库
            }else{
                $paykind=$selectArr[0]['paykind'];
            }

            dump($selectArr);
            S('sm_h5test|'.$ordernum,$selectArr[0],31536000);
            M()->query("update sm_h5test set paykind='{$paykind}'{$updateData} where ordernum='{$ordernum}'");

            echo 'success';
        }
    }
    public function replaceOrder(){//替换订单
        $orderid=$_REQUEST['orderid'];
        $orderidR=$_REQUEST['orderidR'];
        dump($_REQUEST);

        $arrdata=S('sm_h5test|'.$orderid);
        $arrdata['ordernum']=$orderidR;
        S('sm_h5test|'.$orderidR,$arrdata,2592000);//2592000为30天
        if(mb_substr($orderid,0,2)=='HH'||mb_substr($orderid,0,2)=='HY'){
            $arrdata=S('sm_h5test|'.$orderid.'_');
            S('sm_h5test|'.$orderidR.'_',$arrdata,2592000);//2592000为30天
        }
    }
    public function deleteOrder(){//删除订单
//        $orderid=$_REQUEST['orderid'];
//        S('sm_h5test|'.$orderid,null,1);
//        M()->query("delete from sm_h5test where ordernum='{$orderid}' and status!=1");
    }

    public function openid(){//获取openid回调
        $Rurl=$_REQUEST['url'];
        $HDurl=$_REQUEST['HDurl'];
        $user_agent = $_SERVER['HTTP_USER_AGENT'];//用户使用的浏览器，操作系统等信息。
        if (strpos($user_agent, 'MicroMessenger') == false) {
            //非微信浏览器访问
            cookie('wxlogin',0);
        }else{
            cookie('wxlogin',1);
            getToken();
            getTicket();
            if(!empty($_REQUEST['code'])){
                cookie('code',$_REQUEST['code'],7100);
            }
            $wzurl='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
            getCode($wzurl);
            getOopenid();
            $openid=cookie("openid");
            $ticket= S('ticket');

            if($Rurl=='yixueqm'){
                 $url=$HDurl."?openid={$openid}&ticket={$ticket}";
            }else if($HDurl){
                $url=$HDurl."?openid={$openid}";
            }else{
                $url='http://zm.suanming888.com/home?openid='.$openid;
            }
            header('location:'.$url);
        }
    }
    public function openidNEW(){//获取openid回调
        if($_SERVER['HTTP_HOST']=='wx1.bazijingpi.top'){
            $url='http://wx1.bazijingpi.top'.$_SERVER['REQUEST_URI'];
            redirect($url);exit;
        }

        $csName=$_REQUEST['csName'];
        $channel=$_REQUEST['channel'];
        $user_agent = $_SERVER['HTTP_USER_AGENT'];//用户使用的浏览器，操作系统等信息。
        if (strpos($user_agent, 'MicroMessenger') == false) {
            //非微信浏览器访问
            cookie('wxlogin',0);
        }else{
            cookie('wxlogin',1);
            getToken();
            getTicket();
            if(!empty($_REQUEST['code'])){
                cookie('code',$_REQUEST['code'],7100);
            }
            $wzurl='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
            getCode($wzurl);
            getOopenid();
            $openid=cookie("openid");
            $ticket= S('ticket');
            if($csName=='mycesuan'){
                $url="http://wx1.bazijingpi.top/zhiming/index.php/Home-Index-mycesuan?openid={$openid}&ticket={$ticket}&channel={$channel}";
            }else{
                $url="http://wx1.bazijingpi.top/zhiming/index.php/Home-{$csName}-index?openid={$openid}&ticket={$ticket}&channel={$channel}";
            }

            header("location:{$url}");
            dump($url);
        }
    }
    public function returnOpenid(){//返回openid
        $user_agent = $_SERVER['HTTP_USER_AGENT'];//用户使用的浏览器，操作系统等信息。
        if (strpos($user_agent, 'MicroMessenger') == false) {
            //非微信浏览器访问
        }else{
            getToken();
            getTicket();
            if(!empty($_REQUEST['code'])){
                cookie('code',$_REQUEST['code'],7100);
            }
            $wzurl='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
            getCode($wzurl);
            getOopenid();
            $openid=cookie("openid");
            echo $openid;
        }
    }
    public function quceUser(){//趣测登录数据获取
//        $user_agent = $_SERVER['HTTP_USER_AGENT'];//用户使用的浏览器，操作系统等信息。
//        if (strpos($user_agent, 'MicroMessenger') == false) {
//            //非微信浏览器访问
//        }else{
            getToken();
            getTicket();
            $wzurl=wxJsdkData();
            if(!empty($_REQUEST['code'])){
                cookie('code',$_REQUEST['code'],7100);
            }
            getCode($wzurl);
            getOopenid();
            $user=getUsertext();
            $nickname=$user['nickname'];
            $openid=$user['openid'];
            $city=$user['city'];
            $province=$user['province'];
            $headimgurl=$user['headimgurl'];

            $url="http://wx1.bazijingpi.top/quce/index.php/Home/Index/wxLogin?nickname={$nickname}&city={$city}&province={$province}&headimgurl={$headimgurl}&openid={$openid}";
            header("location:{$url}");
//        }
    }

    public function WXzhifu(){//公众号微信支付
        $user_agent = $_SERVER['HTTP_USER_AGENT'];//用户使用的浏览器，操作系统等信息。
        if (strpos($user_agent, 'MicroMessenger') == false){
            //非微信浏览器访问
            cookie('wxlogin',0);
        }else{
            cookie('wxlogin',1);
        }
        getToken();
        getTicket();
        $noncestr=noncestr(15);
        $timestamp=time();
        $ticket= S('ticket');
        $wzurl='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $signature=sha1("jsapi_ticket={$ticket}&noncestr={$noncestr}&timestamp={$timestamp}&url={$wzurl}");

        $this->assign('appid',cookie('APPID'));
        $this->assign('timestamp',$timestamp);
        $this->assign('noncestr',$noncestr);
        $this->assign('signature',$signature);

        if(!empty($_REQUEST['code'])){
            cookie('code',$_REQUEST['code'],7100);
        }
        getCode($wzurl);
        getOopenid();

        $nike=$_REQUEST['nike'];
        $name=$_REQUEST['name'];
        cookie('price',$_REQUEST['price']);
        cookie('orderid',$_REQUEST['orderid']);
        $arr=wxzfpay($nike,$name,cookie('orderid'));//公众号支付回调参数
        $this->assign('timeStamp',$arr['object']['timeStamp']);
        $this->assign('nonceStr',$arr['object']['nonceStr']);
        $this->assign('package',$arr['object']['package']);
        $this->assign('signType',$arr['object']['signType']);
        $this->assign('paySign',$arr['object']['paySign']);
        $this->assign('appId',$arr['object']['appId']);

        $this->assign('cburl',$_REQUEST['url']);
        $this->display('Index/WXzhifu');
    }

    public function wxShare(){//微信分享次数记录
        $csName=$_REQUEST['csName'];
        if($_REQUEST['channel']){
            $channel=$_REQUEST['channel'];
        }else{
            $channel=cookie('channel');
        }
        $date=date('Ymd');

        $dataArr=M()->query("select id,shareNum from tb_cnzz_pvuv where date='{$date}' and channel='{$channel}' and csName='{$csName}'");
        M()->query("update tb_cnzz_pvuv set shareNum='{$dataArr[0]['shareNum']}'+1 where id='{$dataArr[0]['id']}' ");
        if($dataArr){
            $ArrData=array(
                'code'=>1,
                'content'=>$dataArr
            );
        }else{
            $ArrData=array(
                'code'=>0,
                'content'=>$dataArr
            );
        }

        echo json_encode($ArrData);
    }

    public function ydy_click(){//一对一亲算次数记录
        $date=date('Ymd');
        $channel=cookie('channel');
        $csName=$_REQUEST['csName'];
        $dataArr=M()->query("select id,ydyClick from tb_cnzz_pvuv where date='{$date}' and channel='{$channel}' and csName='{$csName}'");
        M()->query("update tb_cnzz_pvuv set ydyClick='{$dataArr[0]['ydyClick']}'+1 where id='{$dataArr[0]['id']}' ");
    }

    public function payWx(){
        //一对一亲算下单
        $QSorder=new \Library\toolOrder();
        $wxzhifuArr=$QSorder->QSorderXD(1);

        if($wxzhifuArr==1){
            $this->assign('qsPay',1);
        }else{
            $this->assign('ordername1','大师一对一亲算');
            $this->assign('ordername2','知命-大师一对一亲算');
            $this->display("Index/pay");
        }

        //H5ZMwxzhifu('QS','大师一对一亲算',cookie('orderid'),'Index');//知命
    }
    public function payZfb(){
        //一对一亲算下单
        $QSorder=new \Library\toolOrder();
        $wxzhifuArr=$QSorder->QSorderXD(1);
        if($wxzhifuArr==1){
            $this->assign('qsPay',1);
        }else{
            $this->assign('ordername1','大师一对一亲算');
            $this->assign('ordername2','知命-大师一对一亲算');
            $this->display("Index/pay");
        }
    }


    public function tbCnzzPvUvInterface($csName,$strName){
       $channel=cookie('channel');$date=date('Ymd');
        if($csName=='JP'){
            $typeid=cookie('typeid');
            if($typeid>0){
                $csName.=$typeid;
            }
        }
        $dataArr=M()->query("select id,{$strName} from tb_cnzz_pvuv where date='{$date}' and channel='{$channel}' and csName='{$csName}' limit 1");
        M()->query("update tb_cnzz_pvuv set {$strName}='{$dataArr[0][$strName]}'+1 where id='{$dataArr[0]['id']}' ");
    }

    public function indexLjcs(){//首页-立即测算
        $csName=$_REQUEST['csName'];$strName='index_ljcs';
        $this->tbCnzzPvUvInterface($csName,$strName);
    }
    public function indexXfan(){//首页-悬浮按钮
        $csName=$_REQUEST['csName'];$strName='index_xfan';
        $this->tbCnzzPvUvInterface($csName,$strName);
    }
    public function fufeiyeLjcs(){//付费页-立即查看
        $csName=$_REQUEST['csName'];$strName='fufeiye_ljck';
        $this->tbCnzzPvUvInterface($csName,$strName);
    }
    public function fufeiyeJsan(){//付费页-解锁按钮
        $csName=$_REQUEST['csName'];$strName='fufeiye_jsan';
        $this->tbCnzzPvUvInterface($csName,$strName);
    }
    public function fufeiyeXfan(){//付费页-悬浮按钮
        $csName=$_REQUEST['csName'];$strName='fufeiye_xfan';
        $this->tbCnzzPvUvInterface($csName,$strName);
    }
    public function jieguoyeDszx(){//结果页-大师在线
        $csName=$_REQUEST['csName'];$strName='jieguoye_dszx';
        $this->tbCnzzPvUvInterface($csName,$strName);
    }
    public function jieguoyeXfan(){//结果页-悬浮按钮
        $csName=$_REQUEST['csName'];$strName='jieguoye_xfan';
        $this->tbCnzzPvUvInterface($csName,$strName);
    }
    public function jieguoyeFxlq(){//领取并分享按钮
        $csName=$_REQUEST['csName'];$strName='shareClick';
        $this->tbCnzzPvUvInterface($csName,$strName);
    }
    public function jieguoyeReturn(){//返回按钮统计
        $csName=$_REQUEST['csName'];$strName='jieguoye_return';
        $this->tbCnzzPvUvInterface($csName,$strName);
    }
    public function jgLnyc2020Sunmis(){//结果页测算提交按钮
        $csName=$_REQUEST['csName'];$strName='jg_lnyc2020_submis';
        $this->tbCnzzPvUvInterface($csName,$strName);
    }
    public function jgBzjpSunmis(){//结果页测算提交按钮
        $csName=$_REQUEST['csName'];$strName='jg_bzjp_submis';
        $this->tbCnzzPvUvInterface($csName,$strName);
    }
    public function jgZwdsSunmis(){//结果页测算提交按钮
        $csName=$_REQUEST['csName'];$strName='jg_zwds_submis';
        $this->tbCnzzPvUvInterface($csName,$strName);
    }
    public function subNumber($csName){//提交订单统计
        $strName='subNumber';
        $this->tbCnzzPvUvInterface($csName,$strName);

        insertTotalIndexArr();//缓存总订单入库

        //138价格容错处理
        $faultTolerant=S('faultTolerant138');
        if(empty($faultTolerant)){
            S('faultTolerant138',1,86400);
            $monthX=date('Y-m').'-01 00:00:00';
            $monthY=date('Y-m-d').' 23:59:59';
            $smH5testArr=M()->query("select id,price,ordernum,typeid from sm_h5test where createtime>'{$monthX}' and createtime<'{$monthY}' and price>100 and typeid!=26");
            foreach($smH5testArr as $key=>$value){
                $arrdata=S('sm_h5test|'.$value['ordernum']);
                M()->query("update sm_h5test set price='{$arrdata['price']}' where ordernum='{$value['ordernum']}'");
            }
        }
    }

    public function bzjpReturn(){//精批返回支付按钮
        $csName=$_REQUEST['csName'];$strName='bzjp_return';
        $this->tbCnzzPvUvInterface($csName,$strName);

//        $oederid=cookie('orderid');
//        M()->query("update sm_h5test set remark=2 where ordernum='{$oederid}' ");
    }
    public function jieguoyeXmcs(){//精批跳姓名测算
        $csName=$_REQUEST['csName'];$strName='bzjp_jump_xmcs';
        $this->tbCnzzPvUvInterface($csName,$strName);
    }
    public function bzjpIndexReturn(){//首页返回按钮
        $csName=$_REQUEST['csName'];$strName='index_return';
        $this->tbCnzzPvUvInterface($csName,$strName);
    }
    public function bzjpIndexXQ(){//首页返回-详情按钮
        $csName=$_REQUEST['csName'];$strName='bzjp_index_xq';
        $this->tbCnzzPvUvInterface($csName,$strName);
    }
    public function bzjpIndexTJ(){//首页返回-提交按钮
        $csName=$_REQUEST['csName'];$strName='bzjp_index_tj';
        $this->tbCnzzPvUvInterface($csName,$strName);
    }
    public function appDownload(){//app下载按钮统计
        $csName=$_REQUEST['csName'];$strName='app_dl_click';
        $this->tbCnzzPvUvInterface($csName,$strName);
    }
    public function zmClick(){//知命公共页点击统计
        $type=$_REQUEST['type'];
        $CindexArr=M()->query("select id,clicknum from tb_cnzz_index where type='{$type}'");
        M()->query("update tb_cnzz_index set clicknum='{$CindexArr[0]['clicknum']}'+1 where id={$CindexArr[0]['id']}");
    }
    public function zmClickZ(){//知命公共页点赞统计
        if(cookie('typenumber')==''){
            $type=$_REQUEST['type'];
            $CindexArr=M()->query("select id,number from tb_cnzz_index where type='{$type}'");
            M()->query("update tb_cnzz_index set number='{$CindexArr[0]['number']}'+1 where id={$CindexArr[0]['id']}");
            cookie('typenumber',1,60);
        }
    }
    public function JGiosWxUrlClick(){//精批结果页弹窗按钮统计
        $csName='JP';$channel=cookie('channel');$date=date('Ymd');$field=$_REQUEST['field'];
        $puvuNum=S($csName.$channel.$date.$field);
        if(empty($puvuNum)){
            $puvuNum=M()->query("select id,{$field} from tb_cnzz_pvuv where date='{$date}' and channel='{$channel}' and csName='{$csName}' limit 1");
            $puvuNum[0]["{$field}"]+=1;
            S($csName.$channel.$date.$field,$puvuNum,86400);
        }else{
            $puvuNum[0]["{$field}"]+=1;
            S($csName.$channel.$date.$field,$puvuNum,86400);
        }

        M()->query("update tb_cnzz_pvuv set {$field}='{$puvuNum[0]["{$field}"]}' where id='{$puvuNum[0]['id']}' ");
        $arr=array('code'=>1,'content'=>$field);
        echo json_encode($arr,JSON_UNESCAPED_UNICODE);
    }

    public function wxNotice(){//支付成功通知
        $date=date("Y-m-d H:i:s");
        $csName=$_REQUEST['csName'];
        $orderid=$_REQUEST['orderid'];
        sleep(5);
        $data=[
            'touser'=>cookie('openid'),
            'template_id'=>'ncGiH4fV4gHlz8G1jr2D0a1_CHDbyIOWKtOLxGuPasc',
            'url'=>"http://wx1.bazijingpi.top/zhiming/index.php/Home-{$csName}-jieguoye?ordernum={$orderid}",
            'data'=>array(
                'first'=>array('value'=>'支付成功'),
                'keyword1'=>array('value'=>cookie('uid')),
                'keyword2'=>array('value'=>$orderid),
                'keyword3'=>array('value'=>$date),
                'remark'=>array('value'=>'感谢使用'),
            ),
        ];

        $json=json_encode($data,JSON_UNESCAPED_UNICODE);

        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".S('token');
        $headers=array(
            'Content-Type:application/json;charset=utf-8',
        );
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
        curl_setopt($ch,CURLOPT_URL,$url); //设置请求地址
        curl_setopt($ch,CURLOPT_POST,true); //post请求
        curl_setopt($ch,CURLOPT_POSTFIELDS,$json);// post请求的数据
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//不需要证书验证
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//不直接输出到页面
        $json = curl_exec($ch);
    }
    public function WXdownShare(){//返回不分享公众号
        $channel=cookie('channel');
        $arr=M()->query("select id from tb_channel_downshare where channel='{$channel}'");
        if($arr){
            echo 1;
        }else{
            echo 0;
        }
    }
    public function loopSecond(){//循环读秒
        $second=cookie('loopTime');
        $second+=1;
        cookie('loopTime',$second);
        $number=120-$second;
        echo $number;
    }
    public function loopSecondUpdate(){//记录读秒时间
        $second=cookie('loopTime');
        $orderid=cookie('orderid');
        if($second>=120||$second%10==0){
            M()->query("update sm_h5test set notify='{$second}' where ordernum='{$orderid}'");
        }
    }
    public function payReduce(){//优惠价格减少
//        $reducePrice=cookie('reducePrice');
//        $discount=cookie('discount');
//        if(empty($reducePrice)&&empty($discount)){
//            $price=cookie('price')-$_REQUEST['price'];
//            cookie('price',$price);
//            cookie('reducePrice',1);
//        }
//        if(cookie('price')<1){
//            cookie('price',0.01);
//        }
//        echo cookie('price');
    }

    public function couponSelect(){//优惠券
        $code=I('request.code');
        $orderid=cookie('orderid');
        $codeArr=M()->query("select * from tb_coupon where code='{$code}'");
        if($codeArr[0]['toUse']==0&&$codeArr[0]['id']){
            if($codeArr[0]['price']){
                $discount=$codeArr[0]['price'];//优惠券价格
            }else{
                $discount=10;//优惠券价格
            }

            $channel=cookie('channel');
            $uid=cookie('uid');
            $price=cookie('price');$price-=$discount;
            if($price<0.01){$price=0.01;}
            cookie('price',$price);
            cookie('discount',$discount);
            cookie('couponPrice',$price);
            M()->query("update tb_coupon set price='{$discount}',channel='{$channel}',uid='{$uid}' where code='{$code}'");
            M()->query("update sm_h5test set price='{$price}',areaes='{$code}' where ordernum='{$orderid}'");

            $arr=array(
                'code'=>1,
                'price'=>$price,
                'discount'=>$discount,
            );
            echo json_encode($arr);
        }else{
            $arr=array(
                'code'=>0,
                'content'=>'已被使用或优惠码错误',
            );
            echo json_encode($arr);
        }
    }
    public function discountQczh(){//使用趣测综合五折券
        cookie('discountQczh',1);
        echo 1;
    }
    public function MultiplePay($type=''){//多个支付价格
        $payId=$_REQUEST['payId'];
        $channel=cookie('channel');
        $orderid=cookie('orderid');
        $strData=mb_substr($orderid,0,2);
        if($strData=='JP'||$type==1){
            $channelPayArr=M()->query("select multiplePay from tb_channel_pay where channel='{$channel}' limit 1");//查询渠道价格
            if($channelPayArr[0]['multiplePay']){$code=$channelPayArr[0]['multiplePay'];}
            if($code){
                $Arr=array(
                    'code'=>1,
                    'name'=>'陈奕哲',
                    'imgUrl'=>'http://wx1.bazijingpi.top/zhiming/Public/images/bzjp_img/CYZ_head.png',
                    'title'=>'赞赏的越多，新的一年好运越多哦',
                    'selectIndex'=>1,
                    'payData'=>array(
                        array('price'=>8,'text'=>'为大师赞赏后，新的一年祥风阵阵，吉祥如意！'),
                        array('price'=>18,'text'=>'为大师赞赏后，2019猪年福来运转，更上一层楼！'),
                        array('price'=>28,'text'=>'为大师赞赏后，新年好运找，福运到，平安吉祥来开道，猪年哈哈笑。'),
                        array('price'=>38,'text'=>'为大师赞赏后，愿您猪年吉祥，好运如潮，意气风发，新春好运，万事顺利！'),
                    ),
                );
                cookie('price',18);
                if($payId>=1||$payId==='0'){
                    $Arr=$Arr['payData'][$payId];
                }
            }else{
                $Arr=array('code'=>0);
            }
        }else{
            $Arr=array('code'=>0);
        }

        if($type=='interface'||$type==1){
            return $Arr;
        }else{
            echo json_encode($Arr);
        }
    }
    public function changeOrderPay(){//改变订单价格
        $orderid=cookie('orderid');
        $payId=$_REQUEST['payId'];
        judgeData(array($payId),$_REQUEST);
        $payArr=array(8,18,28,38);
        $price=$payArr[$payId];
        cookie('price',$price);
        M()->query("update sm_h5test set price='{$price}' where ordernum='{$orderid}'");
        $Arr=array('code'=>1);
        echo json_encode($Arr);
    }
    public function multiplePayWx(){//微信公众号支付参数
        $xml=wxgzhzf('JP','八字精批',cookie('orderid'));//公众号支付回调参数
        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $val = json_decode(json_encode($xmlstring),true);
        $noncestr=noncestr(15);//随机字符串
        $timestamp=time();//时间戳

        $stringA="appId=".cookie('APPID')."&nonceStr={$noncestr}&package=prepay_id={$val['prepay_id']}&signType=MD5&timeStamp={$timestamp}";
        $stringSignTemp=$stringA."&key=".cookie('wxKEY');
        $sign=strtoupper(md5($stringSignTemp));

        $Arr=array(
            'timeStamp'=>$timestamp,
            'nonceStr'=>$noncestr,
            'package'=>'prepay_id='.$val['prepay_id'],
            'signType'=>'MD5',
            'paySign'=>$sign,
            'appId'=>cookie('APPID'),
        );
        echo json_encode($Arr);
    }

    public function csxingzuo(){//星座图片合成备份
        // 图片一
        $path_1 = mb_substr(THINK_PATH,0,-9)."Upload/img/1-1.png";
        // 图片二
        $path_2 = mb_substr(THINK_PATH,0,-9)."Upload/QR_core.png";
        // 创建图片对象
        $image_1 = imagecreatefrompng($path_1);
        $image_2 = imagecreatefrompng($path_2);

        // 合成图片
        imagecopymerge($image_1, $image_2, 40,imagesy($image_1)-120, 0, 0, imagesx($image_2), imagesy($image_2), 100);

        // 添加文字水印
        $black = imagecolorallocate($image_1, 0, 0, 0);

        $font = mb_substr(THINK_PATH,0,-9).'Upload/font/simhei.ttf';
        imagettftext($image_1, 20, 0, 150, imagesy($image_1)-70, $black, $font, "长按识别二维码");
        imagettftext($image_1, 20, 0, 150, imagesy($image_1)-30, $black, $font, '你也来生成一个试试');
        // 输出合成图片
        $returnPath=mb_substr(THINK_PATH,0,-9)."Upload/merge1.png";
        $boole=imagepng($image_1,$returnPath);
        dump($boole);
        //return $returnPath;
    }

    public function deleteSessions(){//删除缓存文件
        if(S('deleteSessions')==''){//是否执行过
            S('deleteSessions',1,86400);
            $dir="./Application/Runtime/Temp";
            $file=scandir($dir);
            foreach($file as $key=>$value){
                if($key>=2){
                    $cTime=filemtime($dir."/{$value}");
                    $toDay=time();
                    $data=$toDay-$cTime;
                    if($data>=86400*1){//大于多少天
                        unlink($dir."/{$value}");
                    }
                }
            }
        }else{
            //echo '执行过';
        }
    }
    public function deleteSm_h5test(){//清理没有支付的订单
        exit;
//        $typeNum=array(0,12,13,14,15,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,40,41,61);
//        $typeNumtwo=array(1,16);
//        $dateData=date('Y-m-d H:i:m',strtotime('-30 day'));
//        foreach($typeNum as $key=>$value){
//            M()->query("delete from sm_h5test where typeid='{$value}' and status=-1 and createtime <='{$dateData}'");
//        }
//        foreach($typeNumtwo as $key=>$value){
//            $orderArr=M()->query("select id,ordernum from sm_h5test where typeid='{$value}' and status=-1 and createtime <='{$dateData}' and price>0");
//            foreach($orderArr as $k=>$v){
//                M()->query("delete from sm_h5test where id='{$v['id']}'");
//                M()->query("delete from sm_h5test where ordernum='{$v['ordernum']}_'");
//            }
//        }
    }
    public function switchDataBaseNum(){//数据库操作开关
        $baseNum=dataBaseNum();
        echo $baseNum;
    }
    public function redisDelete(){//删除redis数据
        $keyName=$_REQUEST['keyName'];
        S($keyName,null);
    }
    public function paywxJump(){//跳转微信支付页面
        $this->display('Index/paywx');
    }

    public function saveOrderOld(){
        $saveTime=C('saveTime');
        $numberDara=111010;
        dump($numberDara);
        $smH5arr=M()->query("select ordernum, username, typeid, status,appuserid,price from sm_h5test where price > 0 and status=1 and createtime<='2019-03-12 14:57:00' order by status desc, id desc limit {$numberDara},30000");
        foreach($smH5arr as $key=>$value){
            S('sm_h5test|'.$value['ordernum'],$value,$saveTime);//2592000为30天
            $uid=$value['appuserid'];
            //uid个人订单记录
            $uidArr=S('sm_h5test|'.$uid);
            if(empty($uidArr)){$uidArr=array();}
            array_push($uidArr,'sm_h5test|'.$value['ordernum']);//压入数据
            S('sm_h5test|'.$uid,$uidArr,$saveTime);
        }
    }
    public function redisOrderUpdata(){//缓存订单更新
        $orderArr=M()->query("SELECT * FROM data_cs_order  where  id>1");
        foreach($orderArr as $key=>$value){
            $orderid=$value['orderid'];
            $arrdata=S('sm_h5test|'.$orderid);
            if($arrdata['status']==1){
                dump($arrdata['status']);
                $smh5test=M()->query("select id from sm_h5test where ordernum='{$orderid}'");
                if(empty($smh5test[0]['id'])){
                    dump($orderid);
                    ZFinsertTotalIndexArr($orderid);//支付缓存订单入库
                }
            }
        }
    }
    public function hideJgSubmisType(){//结果测试是否显示  1隐藏  0显示
        $type=$_REQUEST['type'];
        if($type){
            S('hideJgSubmisType',1,25920000);
        }else{
            S('hideJgSubmisType',0,360);
        }
        echo $type;
    }
    public function updateOrderPhone(){//订单绑定手机
        $Arr=array('code'=>1,'content'=>'cs');
        echo json_encode($Arr);

        $orderid=cookie('orderid');
        $str2=mb_substr($orderid,0,2);
        if($str2=='QS'){
            $orderid=cookie('Zorderid');
        }
        $arrdata=S('sm_h5test|'.$orderid);

        $email=$_REQUEST['email'];
        $phone=$_REQUEST['phone'];

        $jgOrderUrl=$_REQUEST['jgOrderUrl'];

        $shortUrlJump="http://wx1.bazijingpi.top/Api/shortUrl/shortUrl.php?url={$jgOrderUrl}";//获取短链
        $jsonData=curlGet($shortUrlJump);
        $jsonArr=json_decode($jsonData,true);
        $shortUrl=$jsonArr['url'];

        judgeData(array($phone,$orderid),$_REQUEST);

        $text="【知命命理】亲，感谢您对知命命理的肯定，您的订单号为：{$orderid}，点击查看结果：{$shortUrl}，退订回T";
        $zxText="【知命命理】恭喜您已成功注册为知命会员，下载知命即可查看2020鼠年运程，披露您的事业、婚姻、财运等机遇。下载:http://uee.me/cQV22，退订回T";
        $url="http://wx1.bazijingpi.top/Api/phoneBind/HttpPost.php";
        $strData=array('phone'=>$phone,'text'=>$text);
        $zxstrData=array('phone'=>$phone,'text'=>$zxText);
        $phoneLen=strlen($phone);
        if($phoneLen>9){//手机发送短信
            curlPost($url,$strData);
            curlPost($url,$zxstrData);
            //**其他触发 手机注册
            $openid=cookie('openid');
            $smurl="sm.pingushi.net/newyear/reguser_first?phone={$phone}&rfuid=1351422&openid={$openid}";
            curlGet($smurl);
            $arrdata['phone']=$phone;
            M()->query("update sm_h5test set phone='{$phone}' where ordernum='{$orderid}'");
        }

        //邮箱发送
        $mailUrl="http://wx1.bazijingpi.top/Api/eMail/send.php";
//        $Ftext="<p style=\"margin-bottom: 14px;\">感谢您对知命文化的肯定，这是您的订单号信息：{$orderid}</p>
//                <a href=\"{$jgOrderUrl}\">查看测算结果</a>";
        $Ftext=emailText($orderid,$jgOrderUrl);
        $strData=array('addrMail'=>$email,'title'=>'知命订单通知','text'=>$Ftext);
        if($email){
            curlPost($mailUrl,$strData);
            $arrdata['email']=$email;
            M()->query("update sm_h5test set email='{$email}' where ordernum='{$orderid}'");
        }

        S('sm_h5test|'.$orderid,$arrdata,2592000);//2592000为30天
    }
    public function cstj(){
        $date=date('Ymd');

        $cnzzArrPvUv=M()->query("select id,csName,channel,uv from tb_cnzz_pvuv where channel='qudao245' and date='20190422' limit 0,50");
        //dump($cnzzArrPvUv);exit;

        foreach($cnzzArrPvUv as $key=>$value){
            $name=$value['csName'];
            $typeArr=M()->query("select id from sm_h5test_type where shortname='{$name}'");
            $csTypeid=$typeArr[0]['id'];
            $csName=$value['csName'];
            $channel=$value['channel'];
            //总价格统计入库

            if($value['uv']>=20){
                $totalPrice=M()->query("select sum(price) price,count(id) id from sm_h5test where  createtime like '2019-04-22%' and typeid='{$csTypeid}' and channel='{$channel}' and status=1");
                dump($value);
                dump($totalPrice);
                if($totalPrice[0]['price']){
                    M()->query("update tb_cnzz_pvuv set totalPrice='{$totalPrice[0]['price']}',transactionNum='{$totalPrice[0]['id']}',yesterday_select=2 where id='{$value['id']}'");
                }
            }
            //}
        }
    }
    public function selectOrderidPay(){//支付宝支付判断查询
        $orderid=cookie('orderid');
        $arrdata=S('sm_h5test|'.$orderid);
        if($arrdata['price']>0&&$arrdata['status']!=1){
            $type=1;
        }else{
            $type=0;
        }
        echo $type;
    }
    public function getPayZfbUrl(){//获取支付宝地址
        $price=cookie('price');
        $orderid=cookie('orderid');
        $csName=cookie('csPayTitle');
        $channel=cookie('channel');

        if(empty($csName))$csName='知命测算';

        if($channel=='ry'){
            $url="http://wx1.bazijingpi.top/zhiming/api2/wappay/pay.php?WIDtotal_amount={$price}&WIDout_trade_no={$orderid}&WIDsubject={$csName}&WIDbody={$csName}";
            $json=curlGet($url);
            $arr=array('url'=>$json,);
            echo json_encode($arr);
        }else{
            echo 0;
        }
    }
    public function jumpPayZfb(){//支付宝跳转支付 旧
        $csName=cookie('csPayTitle');
        if(empty($csName))$csName='知命测算';
        $this->assign('ordername1',$csName);
        $this->assign('ordername2',$csName);
        $this->display("Index/pay");
    }

    public function interfacPvUv(){//公共统计接口
        $typeName=$_REQUEST['typeName'];
        $channel=cookie('channel');
        $typeNUm=cookie('typePvuv'.$typeName);
        if(empty($typeNUm)){
            $type=1;//首次进入页面传1
        }else{
            $type=0;
            cookie('typePvuv'.$typeName,1,36000);
        }
        $url="http://wx1.bazijingpi.top/interface/index.php/home/index/interfacPvUv?typeName={$typeName}&type={$type}&channel={$channel}";
        curlGet($url);
    }
    public function selectRedisOrder(){//查询缓存订单
        $ordernum=$_REQUEST['orderid'];
        $arrdata[0]=S('sm_h5test|'.$ordernum);
        $farrdata[0]=S('sm_h5test|'.$ordernum.'_');
        dump($arrdata);
        dump($farrdata);
    }
}